package com.miku.blog.utils;

import com.miku.blog.domain.pojo.IpAddressesDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author shkstart
 * @create ${}YEAR-05-26 2:07
 */
@Slf4j
public class IpAddressesUtils {
    private static final String IP_DELIMITER = ",";
    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST_IP1 = "0:0:0:0:0:0:0:1";
    private static final String LOCALHOST_IP2 = "127.0.0.1";

    /**
     * 获取ip地址
     * 使用Nginx等反向代理软件， 则不能通过request.getRemoteAddr()获取IP地址
     * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
     */

    public static String getIp(HttpServletRequest request) {

        String ip = request.getHeader("X-real-ip");
        //以下两个获取在k8s中，将真实的客户端IP，放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。

        if (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Original-Forwarded-For");
        }
        if (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        //获取nginx等代理的ip
        if (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }
        if (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (!StringUtils.hasText(ip) || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        //兼容k8s集群获取ip
        if (!StringUtils.hasText(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (LOCALHOST_IP2.equalsIgnoreCase(ip) || LOCALHOST_IP1.equalsIgnoreCase(ip)) {
                //根据网卡取本机配置的IP
                InetAddress iNet;
                try {
                    iNet = InetAddress.getLocalHost();
                    ip = iNet.getHostAddress();
                } catch (UnknownHostException e) {
                    log.error("IPUtils ERROR ", e);
                }
            }
        }

        //使用代理，则获取第一个IP地址
        if (StringUtils.hasText(ip) && ip.indexOf(IP_DELIMITER) > 0) {
            ip = ip.substring(0, ip.indexOf(IP_DELIMITER));
        }


        return ip;
    }


    public static IpAddressesDetail getIpAddressesDetail(RestTemplate restTemplate) {
        String host = "http://opendata.baidu.com/api.php?query=";
        String ip = getIp(HttpUtils.getHttpServletRequest());
        String variable = "&co=&resource_id=6006&oe=utf8";

        StringBuilder url
                = new StringBuilder()
                .append(host)
                .append(ip)
                .append(variable);

        IpAddressesDetail ipAddressesDetail;
        try {
            ipAddressesDetail
                    = restTemplate.getForObject(url.toString(), IpAddressesDetail.class);
        } catch (RestClientException e) {
            log.error(">>> IP查询接口异常 <<<", e);
            ipAddressesDetail = new IpAddressesDetail();
        }

        ipAddressesDetail.setIp(ip);

        return ipAddressesDetail;
    }


}
